package archimede;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Scanner;
import java.util.StringTokenizer;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextPane;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;

import net.miginfocom.swing.MigLayout;


public class PotenzialiVerticali extends JPanel {

	private StartingWindow st;

	private JButton addRilevazione = new JButton(new ImageIcon(ClassLoader.getSystemResource("plus.png")));
	private ArrayList<TablePotenziali> values = new ArrayList<TablePotenziali>();
	private int count = 0;

	private JButton upload1 = new JButton(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
	private JButton upload2 = new JButton(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
	private String lastPath = "";
	private String pathIm1 = "";
	private String pathIm2 = "";
	private String sourceIm1 = "";
	private String sourceIm2 = "";
	private String sufixIm1 = "";
	private String sufixIm2 = "";
	private JPanel photo = new JPanel();

	private JTextPane note = new JTextPane();

	private String directoryProject;

	protected void paintComponent(Graphics g) {
		setOpaque(false);
		g.drawImage((new ImageIcon(ClassLoader.getSystemResource("sfondo.jpg"))).getImage(), 0, 0, null);
		super.paintComponent(g);
	}

	public PotenzialiVerticali(final StartingWindow st) {
		super();
		this.st = st;

		Properties pc = System.getProperties();
		String homePath = pc.getProperty("user.home");
		directoryProject = homePath + pc.getProperty("file.separator") + "ArchimedeSuper" + pc.getProperty("file.separator") + "aaAAzzZZ"
				+ pc.getProperty("file.separator");
		addRilevazione.setBorder(null);
		addRilevazione.setContentAreaFilled(false);
		addRilevazione.setRolloverEnabled(true);
		addRilevazione.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("plus_roll.png")));
		RoundedPanel punto = new RoundedPanel("Punto misurazione");
		setCell(punto);
		punto.setPreferredSize(new Dimension(210, 45));
		RoundedPanel t_verticale = new RoundedPanel("Tensione verticale");
		setCell(t_verticale);
		RoundedPanel p_verticale = new RoundedPanel("Criticita' potenziale");
		setCell(p_verticale);

		JLabel noteLabel = new JLabel("Note");
		noteLabel.setFont(new Font("Arial", Font.BOLD, 20));

		note.setBorder(BorderFactory.createLineBorder(Color.GRAY));
		note.setFont(new Font("Arial", Font.PLAIN, 16));
		note.setPreferredSize(new Dimension(700, 100));

		addRilevazione.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				values.add(new TablePotenziali(PotenzialiVerticali.this, count));
				add(values.get(count), "cell 0 " + (1 + ++count) + " 7 1 , gapleft 15");
				// count++;
				if (count < 15)
					add(addRilevazione, "cell 0 " + (2 + count) + " , gapleft 15");
				else
					remove(addRilevazione);
				st.refresh();
			}
		});
		upload1.setBorder(null);
		upload1.setContentAreaFilled(false);
		upload1.setRolloverEnabled(true);
		upload1.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("upload_icon.jpg")));
		upload1.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser chooser = new JFileChooser();
				chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
				ImagePreviewPanel preview = new ImagePreviewPanel();
				chooser.setAccessory(preview);
				chooser.addPropertyChangeListener(preview);
				lastPath = st.getPath();
				if (lastPath.equals(""))
					chooser.getCurrentDirectory();
				else
					chooser.setCurrentDirectory(new File(lastPath));
				int returnValue = chooser.showOpenDialog(upload1);

				if (returnValue == JFileChooser.APPROVE_OPTION) {
					String sourcePath = chooser.getSelectedFile().toString();
					st.setPath(sourcePath);
					lastPath = sourcePath;
					StringTokenizer tok = new StringTokenizer(sourcePath, ".");
					String sufix = "";
					while (tok.hasMoreTokens())
						sufix = tok.nextToken();

					sourceIm1 = sourcePath;
					ImageIcon tmp = new ImageIcon(sourcePath);
					tmp.setImage(tmp.getImage().getScaledInstance(250, 200, Image.SCALE_AREA_AVERAGING));

					String destPath = directoryProject + "1verticali" + "." + "jpg";
					pathIm1 = destPath;
					sufixIm1 = sufix;

					upload1.setIcon(tmp);
					photo.add(upload2, "cell 1 0");
					st.refresh();
				}
			}
		});

		upload2.setBorder(null);
		upload2.setContentAreaFilled(false);
		upload2.setRolloverEnabled(true);
		upload2.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("upload_icon.jpg")));
		upload2.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser chooser = new JFileChooser();
				chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
				ImagePreviewPanel preview = new ImagePreviewPanel();
				chooser.setAccessory(preview);
				chooser.addPropertyChangeListener(preview);
				lastPath = st.getPath();
				if (lastPath.equals(""))
					chooser.getCurrentDirectory();
				else
					chooser.setCurrentDirectory(new File(lastPath));
				int returnValue = chooser.showOpenDialog(upload2);

				if (returnValue == JFileChooser.APPROVE_OPTION) {
					String sourcePath = chooser.getSelectedFile().toString();
					st.setPath(sourcePath);
					lastPath = sourcePath;
					StringTokenizer tok = new StringTokenizer(sourcePath, ".");
					String sufix = "";
					while (tok.hasMoreTokens())
						sufix = tok.nextToken();

					sourceIm2 = sourcePath;
					ImageIcon tmp = new ImageIcon(sourcePath);
					tmp.setImage(tmp.getImage().getScaledInstance(250, 200, Image.SCALE_AREA_AVERAGING));

					String destPath = directoryProject + "2verticali" + "." + "jpg";
					pathIm2 = destPath;
					sufixIm2 = sufix;

					upload2.setIcon(tmp);
					st.refresh();
				}
			}
		});

		MouseAdapter ml1 = new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.getButton() == MouseEvent.BUTTON3) {
					int res = JOptionPane.showConfirmDialog(null, "Eliminare foto?", "Attenzione", 0);
					if (res == 0) {
						if (!pathIm2.equals("")) {
							pathIm1 = pathIm2.replace("2v", "1v");
							sufixIm1 = sufixIm2;
							sourceIm1 = sourceIm2;
							pathIm2 = "";
							sufixIm2 = "";
							sourceIm2 = "";
							upload1.setIcon(upload2.getIcon());
							upload2.setIcon(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));

						} else {
							pathIm1 = "";
							sufixIm1 = "";
							sourceIm1 = "";
							upload1.setIcon(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
							try {
								photo.remove(upload2);
							} catch (Exception noRemove) {
								//
							}
						}
					}
				}
			}
		};
		upload1.addMouseListener(ml1);
		MouseAdapter ml2 = new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.getButton() == MouseEvent.BUTTON3) {
					int res = JOptionPane.showConfirmDialog(null, "Eliminare foto?", "Attenzione", 0);
					if (res == 0) {

						upload2.setIcon(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
						pathIm2 = "";
						sufixIm2 = "";
						sourceIm2 = "";

					}
				}
			}
		};
		upload2.addMouseListener(ml2);
		ClipboardPopupMenu cb = ClipboardPopupMenu.installForComponent(note);
		cb.addCopyFunction("Copia");
		cb.addCutFunction("Taglia");
		cb.addPasteFunction("Incolla");

		photo.setLayout(new MigLayout());
		photo.setOpaque(false);
		photo.add(upload1, "cell 0 0");

		setLayout(new MigLayout());
		add(photo, "dock north , gapleft 15");
		add(punto, "cell 1 0 , gapleft 10");
		add(t_verticale, "cell 2 0");
		add(p_verticale, "cell 3 0");
		add(addRilevazione, "cell 0 1 , gapleft 15");
		add(note, "dock south , gapleft 15");
		add(noteLabel, "dock south , gapleft 15");

	}

	public void setCell(JComponent c) {
		// c.setBorder(BorderFactory.createLineBorder(Color.GRAY));
		// c.setFont(new Font("TimesRoman", Font.PLAIN, 16));
		c.setPreferredSize(new Dimension(210, 45));
		c.setOpaque(false);
		// c.setBackground(new Color(238, 131, 107));
	}

	public void resize(File in, int w, int h, String formato, String out) throws IOException {
		Image newImg = ImageIO.read(in).getScaledInstance(w, h, Image.SCALE_SMOOTH);
		BufferedImage bim = new java.awt.image.BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		bim.createGraphics().drawImage(newImg, 0, 0, null);
		FileOutputStream fos = new FileOutputStream(out);
		ImageIO.write(bim, formato, fos);
		fos.close();
	}

	public boolean save() {
		boolean done = true;
		if (!sourceIm1.equals("") && !sourceIm1.equals(pathIm1))
			try {
				resize(new File(sourceIm1), 250, 200, "jpg", pathIm1.replace("aaAAzzZZ", st.getProject()));
			} catch (Exception e) {
				sourceIm1 = "";
				pathIm1 = "";
				upload1.setIcon(new ImageIcon(ClassLoader.getSystemResource("upload_icon_err.png")));
				done = false;
				e.printStackTrace();
			}
		if (!sourceIm2.equals("") && !sourceIm2.equals(pathIm2))
			try {
				resize(new File(sourceIm2), 250, 200, "jpg", pathIm2.replace("aaAAzzZZ", st.getProject()));
			} catch (Exception e) {
				sourceIm2 = "";
				pathIm2 = "";
				upload2.setIcon(new ImageIcon(ClassLoader.getSystemResource("upload_icon_err.png")));
				done = false;
				e.printStackTrace();
			}

		return done;
	}

	public String print() {
		String print = "";
		print = print + "\n#" + count;
		print = print + "\n#" + pathIm1.replace("aaAAzzZZ", st.getProject());
		print = print + "\n#" + pathIm2.replace("aaAAzzZZ", st.getProject());
		for (int i = 0; i < count; i++) {
			print = print + values.get(i).print();
		}
		print = print + "\n#start";
		print = print + "\n" + note.getText();

		print = print + "\n@@PotenzialiVerticali";

		return print;
	}

	public void setElement(String data) {
		Scanner c = new Scanner(data);
		c.nextLine();
		String prova = c.nextLine().substring(1);
		count = Integer.parseInt(prova);
		sourceIm1 = c.nextLine().substring(1);
		if (sourceIm1.contains("1verticali")) {

			pathIm1 = directoryProject.replace("aaAAzzZZ", st.getProject()) + "1verticali." + "jpg";
			sourceIm1 = pathIm1;
			upload1.setIcon(new ImageIcon(pathIm1));
			photo.add(upload2, "cell 1 0");
		} else
			sourceIm1 = "";
		sourceIm2 = c.nextLine().substring(1);
		if (sourceIm2.contains("2verticali")) {

			pathIm2 = directoryProject.replace("aaAAzzZZ", st.getProject()) + "2verticali." + "jpg";
			sourceIm2 = pathIm2;
			upload2.setIcon(new ImageIcon(pathIm2));
		} else
			sourceIm2 = "";
		String tmp = c.nextLine();
		while (c.hasNextLine()) {
			tmp = tmp + "\n" + c.nextLine();
		}
		Scanner scanValue = new Scanner(tmp);
		for (int i = 0; i < count; i++) {
			values.add(new TablePotenziali(PotenzialiVerticali.this, i));
			add(values.get(i), "cell 0 " + (1 + i) + " 7 1 , gapleft 15");
			if (count < 15)
				add(addRilevazione, "cell 0 " + (2 + i) + " , gapleft 15");
			else
				remove(addRilevazione);

			String valueTable = scanValue.nextLine().substring(1);
			for (int j = 0; j < 2; j++) {
				valueTable = valueTable + "\n" + scanValue.nextLine().substring(1);
			}
			values.get(i).setElement(valueTable);
		}
		scanValue.nextLine();
		String tp = "";
		while (scanValue.hasNextLine()) {
			tp = tp + scanValue.nextLine() + "\n";
		}
		if (!tp.equals(""))
			tp = tp.substring(0, tp.length() - 1);
		note.setText(tp);
		st.refresh();
	}

	public void removeTabel(int line) {
		count--;
		remove(values.get(line));
		values.remove(line);
		for (int i = line; i < count; i++) {
			add(values.get(i), "cell 0 " + (1 + i) + " 7 1");
			values.get(i).setCount(i);
		}

		if (count < 15)
			add(addRilevazione, "cell 0 " + (2 + count));
		else
			remove(addRilevazione);
		st.refresh();
	}

	public void replace(String newName, String oldName) {
		sourceIm1 = pathIm1;
		sourceIm2 = pathIm2;
		sufixIm1 = sourceIm1.substring(pathIm1.indexOf(".") + 1);
		sufixIm2 = sourceIm2.substring(pathIm2.indexOf(".") + 1);
		pathIm1 = pathIm1.replace(oldName, "aaAAzzZZ");
		pathIm2 = pathIm2.replace(oldName, "aaAAzzZZ");
	}
}
